package org.komarichin.jdo.dao;

import org.apache.commons.lang.StringUtils;
import org.komarichin.beans.IGenericEntity;
import org.komarichin.beans.ILanguage;
import org.komarichin.beans.dao.IGenericLanguageDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import javax.jdo.Query;
import java.util.Collection;

/**
 * User: Mykhaylo Komarichyn
 * Date: 17.03.2010
 * Time: 12:10:57
 */
@Transactional(readOnly = true)
public abstract class JdoGenericLanguageDAOSupport<T extends IGenericEntity<PK>, PK>
        extends JdoGenericDAOSupport<T, PK>
        implements IGenericLanguageDAO<T, PK> {

    private static final Logger log = LoggerFactory.getLogger(JdoGenericLanguageDAOSupport.class);

    @SuppressWarnings("unchecked")
    protected JdoGenericLanguageDAOSupport(Class<T> type) {
        super(type);
    }

    @Override
    public int getCountEntities(ILanguage lang) {
        int result = getAll(lang).size();
        log.info("get count entities# result: {}", result);
        return result;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Collection<T> getEntityByParams(int start, int limit, String fieldName, boolean order, ILanguage lang) {
        log.info("get articles# start: {}, limit: {}, field: {}, order: {}, language: {}", new Object[]{start, limit, fieldName, order, lang});
        StringBuilder buff = new StringBuilder();
        if (StringUtils.isNotBlank(fieldName)) {
            buff.append(fieldName);
        } else {
            buff.append(" id ");
        }
        buff.append(order ? " asc " : " desc ");

        if (limit == 0) {
            limit = 20;
        }

        log.debug("query string: {}", buff.toString());

        Query query = getPersistenceManager().newQuery(getType());
        if (lang != null) {
            query.setFilter("language == pLang || language == 0");
            query.declareParameters(lang.getId().getClass().getSimpleName() + " pLang");
        }

        query.setOrdering(buff.toString());
        query.setRange(start, start + limit);
        Collection<T> result = (Collection<T>) query.execute(lang);
        result.size();
        log.debug("result size: {}", result.size());
        return result;
    }

    @Override
    @SuppressWarnings("unchecked")
    public Collection<T> getAll(ILanguage lang) {
        log.debug("get all for language: {}", lang);
        Collection<T> result = getJdoTemplate().find(getType(), "language == pLang || language == 0", lang.getId().getClass().getSimpleName() + " pLang", lang);
        result.size();
        log.debug("result size: {}", result.size());
        return result;
    }

}
